package org.luxor.commons.core.utils.encrypt;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * AES对称加密解密工具类<对称加解密算法>
 * <p>
 * 使用AES加密解密 AES-128-ECB加密，常用于对mysql中数据的加密处理
 * <p>
 * 数据库AES加密解密方式如下
 * -- 加密
 * SELECT to_base64(AES_ENCRYPT('password','jkl;POIU1234++=='));
 * -- 解密
 * SELECT AES_DECRYPT(from_base64('8G9m8VNJZctBNIyz9swKQw=='),'jkl;POIU1234++==');
 *
 * @author Joye
 */
public class AesEncryptUtils {
    private static final String AES_PKCS5P = "AES/ECB/PKCS5Padding";
    private static final String AES = "AES";

    /**
     * !!! 禁止随意修改，会影响历史账号的登录密码验证
     */
    public static String AES_DATA_SECURITY_KEY = "jkl;POIU1234++==";

    /**
     * 加密(AES_ENCRYPT)
     *
     * @param plaintext 明文
     * @param key       钥匙
     * @return ciphertext 密文(Base64)
     */
    public static String encrypt(String plaintext, String key) {
        if (StringUtils.isEmpty(plaintext) || StringUtils.isEmpty(key)) {
            return plaintext;
        }
        try {
            byte[] raw = key.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, AES);
            // "算法/模式/补码方式"
            Cipher cipher = Cipher.getInstance(AES_PKCS5P);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
            // 此处使用BASE64做转码功能，同时能起到2次加密的作用。
            return Base64.encodeBase64String(encrypted);
        } catch (Exception ex) {
            throw new RuntimeException("加密(AES_ENCRYPT)失败", ex);
        }

    }

    /**
     * 解密(AES_DECRYPT)
     *
     * @param ciphertext 密文(Base64)
     * @param key        钥匙
     * @return plaintext 明文
     */
    public static String decrypt(String ciphertext, String key) {
        if (StringUtils.isEmpty(ciphertext) || StringUtils.isEmpty(key)) {
            return ciphertext;
        }
        try {
            byte[] raw = key.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, AES);
            Cipher cipher = Cipher.getInstance(AES_PKCS5P);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] original = cipher.doFinal(Base64.decodeBase64(ciphertext));
            return new String(original, StandardCharsets.UTF_8);
        } catch (Exception ex) {
            throw new RuntimeException("解密(AES_DECRYPT)失败", ex);
        }
    }

    /**
     * 加密
     *
     * @param plaintext 明文
     * @return ciphertext 密文
     */
    public static String encrypt(String plaintext) {
        return encrypt(plaintext, AES_DATA_SECURITY_KEY);
    }

    /**
     * 解密
     *
     * @param ciphertext 密文
     * @return plaintext 明文
     */
    public static String decrypt(String ciphertext) {
        return decrypt(ciphertext, AES_DATA_SECURITY_KEY);
    }

}
